package com.dlc.shop.mp.common.platform.controller;

import com.dlc.shop.common.response.ServerResponseEntity;
import com.dlc.shop.mp.common.model.WeixinSubscribe;
import com.dlc.shop.mp.common.service.WeixinSubscribeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @author lgh on 2019/01/16.
 */
@RestController
@RequestMapping("/weixin/subscribe")
@Tag(name = "平台端微信关注回复接口")
@AllArgsConstructor
public class WeixinSubscribeController {

    private final WeixinSubscribeService weixinSubscribeService;

    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('weixin:subscribe:page')")
    @Operation(summary = "分页获取微信关注回复数据")
    public ServerResponseEntity<List<WeixinSubscribe>> page(){
        List<WeixinSubscribe> list =  weixinSubscribeService.listWeixinSubscribeAndMaterial();
        for (WeixinSubscribe weixinSubscribe : list) {
            weixinSubscribe.setContent(weixinSubscribe.getContent());
        }
        return ServerResponseEntity.success(list);
    }

    @PostMapping
    @PreAuthorize("@pms.hasPermission('weixin:subscribe:save')")
    @Operation(summary = "保存微信关注回复数据")
    public ServerResponseEntity<Void> save(@RequestBody @Valid WeixinSubscribe weixinSubscribe){
        weixinSubscribe.setContent(weixinSubscribe.getContent());
        weixinSubscribe.setCreateTime(new Date());
        weixinSubscribeService.save(weixinSubscribe);
        weixinSubscribeService.removeWeixinSubscribeAndMaterial();
        return ServerResponseEntity.success();
    }

    @PutMapping
    @PreAuthorize("@pms.hasPermission('weixin:subscribe:update')")
    @Operation(summary = "修改微信关注回复数据")
    public ServerResponseEntity<Void> update(@RequestBody @Valid WeixinSubscribe weixinSubscribe){
        weixinSubscribe.setContent(weixinSubscribe.getContent());
        weixinSubscribeService.updateById(weixinSubscribe);
        weixinSubscribeService.removeWeixinSubscribeAndMaterial();
        return ServerResponseEntity.success();
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('weixin:subscribe:delete')")
    @Operation(summary = "通过id删除微信关注回复数据")
    @Parameter(name = "id", description = "id" , required = true)
    public ServerResponseEntity<Void> delete(@PathVariable Long id){
        weixinSubscribeService.removeById(id);
        weixinSubscribeService.removeWeixinSubscribeAndMaterial();
        return ServerResponseEntity.success();
    }
}
